#include "logindialog.h"
#include "ui_logindialog.h"
#include "settings.h"
#include "engine.h"


#include <QDesktopServices>
#include <QUrl>
#include <QWebElement>
#include <QWebFrame>

QString getver = "2.2.2";
logindialog::logindialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::logindialog)
{
    ui->setupUi(this);
    logindialog::setWindowFlags(Qt::SplashScreen);
    ui->webView->setStyleSheet("background:transparent");
    ui->webView->setAttribute(Qt::WA_TranslucentBackground);
    ui->res_label->setText(tr("Your version is: ") + getver);
}

logindialog::~logindialog()
{
    delete ui;
}

void logindialog::on_OK_Button_clicked()
{   if (ui->webView->url() == QUrl("http://junbach.com/customs/qs_validate.php")) {
        QWebElement e = ui->webView->page()->mainFrame()->findFirstElement("span#success");
        QString ver = ui->webView->page()->mainFrame()->findFirstElement("b#version").toPlainText();
        QString username = e.toPlainText();
        if (!username.isEmpty()) {
            if (ver.contains(getver, Qt::CaseInsensitive)) {
                Config.UserName = username;
                Config.setValue("Username",Config.UserName);
                accept();
            } else { ui->res_label->setText(tr("Please update your game. Your version is") + getver);}
        } else {
            ui->res_label->setText(tr("Login failed. Click the button to login again"));
        }
    } else {
        ui->res_label->setText(tr("You need login first to access the game."));
        return;
    }

}

void logindialog::on_Cancel_Button_clicked()
{
    qApp->quit();
}


void logindialog::on_reload_Button_clicked()
{
    ui->webView->load(QUrl("http://junbach.com/customs/qs_login.php"));
}

void logindialog::on_update_Button_clicked()
{
    QDesktopServices::openUrl(QUrl("http://junbach.com/goc-game/hoi-tam-quoc/"));
}
